<?php

class UCUserSyncBehavior extends CActiveRecordBehavior{

	public $oldPassword;
	public $oldEmail;
	public $ucUserid;
	public function afterFind($event) {
		$this->oldPassword = $this->owner->worker_password;
		$this->oldEmail = CHtml::value($this->owner, 'profile.email');
	}
	
	public function beforeSave($event) {
		$owner = $this->getOwner();
		$ucClient = Yii::app()->ucClient;
		$obj = MemberUcRelated::model()->countByAttributes(array('worker_id'=>$owner->id,'member_type'=>get_class($owner)));
		if ($owner->isNewRecord || !$obj) {
			$result = $ucClient->user->userRegister(
				$owner->worker_name,$owner->worker_password,CHtml::value($owner, 'profile.email')
			);
		} else {
			$result = $ucClient->user->userEdit(
				$owner->worker_name,
				$this->oldPassword,
				$owner->worker_password, 
				$this->oldEmail == CHtml::value($owner, 'profile.email') 
					? null : CHtml::value($owner, 'profile.email'
				)
			);
		}
		if(!$result->isError) {
			$this->ucUserid = $result->toString();
		} else {
			$owner->addError('worker_name', $result->errorMsg);
		}
	}
	
	public function afterSave($event) {
		
		$owner = $this->getOwner();
		$model = new MemberUcRelated();
		
		$ucClient = Yii::app()->ucClient;
		$obj = $model->countByAttributes(array('worker_id'=>$owner->id,'member_type'=>get_class($owner)));
		
		if (($owner->isNewRecord || !$obj) && $this->ucUserid) {
			$model->worker_id = $owner->id;
			$model->uid = $this->ucUserid;
			$model->member_type = get_class($owner);
			$model->save();
		}
	}
	
	public function getUcRelated() {
		$owner = $this->getOwner();
		return MemberUcRelated::model()->findByAttributes(array('worker_id'=>$owner->id,'member_type'=>get_class($owner)));
	}
	
	public function getUcid() {
		$model = $this->getUcRelated();
		return is_object($model) ? $model->uid : '';
	}
}

?>